package com.easycarebn.main.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.easycarebn.main.adapter.AutoCompleteAdapter;
import com.easycarebn.main.utils.IDialogResult;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.ItemRadioSpin;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.controller.SuggestNameType;
import com.easycarebn.request.data.ContactInfoResponse;
import com.easycarebn.request.data.DataItem;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.service.location.LocationServiceManager;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class FragmentHome extends android.support.v4.app.Fragment {
    private static final int DEFAULT_VALUE = 0;

    private View mView;
    private static FragmentHome fragmentHome = null;
    private IResult callIResult;
    private TextView mTvSpin1;
    private TextView mTvSpin2;
    private TextView mTvSpin3;
    private TextView tvCopyRight;
    private TextView tvHotline;
    private TextView tvEmail;

    private TextView mTvSpinMainMenu;
    public static TextView mSmessage;
    private CheckBox mChkSearchByName;
    private AutoCompleteTextView mEdkeySearch;
    private static boolean isSearchbyName;

    private View mLayoutSpin2;

    private final int INDEX_MENU_CLINIC = 2;
    private final int INDEX_MENU_HOME_SERVICE = 3;
    private final int INDEX_MENU_CITY = 5;

    private final int INDEX_SUB_MENU_SPECIALITY_TYPE = 11;
    private final int INDEX_SUB_MENU_SPECIALITY_DETAIL = 12;

    private int mSelectedMenu = SuggestNameType.DOCTOR.getCode();
    private int mSelectedSpin1 = DEFAULT_VALUE;
    private int mSelectedSpin2 = DEFAULT_VALUE;
    private int mSelectedSpin3 = DEFAULT_VALUE;
    AutoCompleteAdapter adapter;
    private List<ItemRadioSpin> mMainMenu;

    private void resetSpin2() {
        if (mSelectedMenu == SuggestNameType.CLINIC.getCode()) {
            mTvSpin1.setText(getString(R.string.select_loai_phong_kham));
        } else if (mSelectedMenu == SuggestNameType.DOCTOR.getCode()) {
            mTvSpin2.setText(getString(R.string.select_khoa));
        } else if (mSelectedMenu == SuggestNameType.HOME_SERVICE.getCode()) {
            mTvSpin1.setText(getString(R.string.select_loai_dich_vu));
        }
    }

    private OnClickListener mSpinClicked = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int viewId = v.getId();
            if (viewId == R.id.sp_menu_dichvu) {
                if (adapter != null) {
                    adapter.clear();
                }

                if (mEdkeySearch != null && !mChkSearchByName.isChecked()) {
                    mEdkeySearch.setVisibility(View.GONE);
                }
                Utils.showDropdow(mSelectedMenu, getActivity(), mMainMenu, new IDialogResult() {

                    @Override
                    public void onResultDropdow(ItemRadioSpin item, int type) {
                        mTvSpinMainMenu.setText(item.getLabel());
                        mSelectedMenu = item.getId();
                        if (mSelectedMenu == SuggestNameType.CLINIC.getCode()) {
                            mLayoutSpin2.setVisibility(View.GONE);
                            mTvSpin1.setText(getString(R.string.select_loai_phong_kham));
                        } else if (mSelectedMenu == SuggestNameType.DOCTOR.getCode()) {
                            mLayoutSpin2.setVisibility(View.VISIBLE);
                            mTvSpin1.setText(getString(R.string.select_chuyenkhoa));
                            mTvSpin2.setText(getString(R.string.select_khoa));
                        } else if (mSelectedMenu == SuggestNameType.HOME_SERVICE.getCode()) {
                            mLayoutSpin2.setVisibility(View.GONE);
                            mTvSpin1.setText(getString(R.string.select_loai_dich_vu));
                        }
                        mSelectedSpin1 = DEFAULT_VALUE;
                        mSelectedSpin2 = DEFAULT_VALUE;
                        mSelectedSpin3 = DEFAULT_VALUE;
                    }
                }, null, mSelectedMenu);
                return;
            }
            int menuId = INDEX_MENU_CITY;
            if (mSelectedMenu == SuggestNameType.DOCTOR.getCode()) {
                if (viewId == R.id.lblSpin1) {
                    menuId = INDEX_SUB_MENU_SPECIALITY_TYPE;
                } else if (viewId == R.id.lblSpin2) {
                    menuId = INDEX_SUB_MENU_SPECIALITY_DETAIL;
                }
            } else if (mSelectedMenu == SuggestNameType.HOME_SERVICE.getCode()) {
                if (viewId == R.id.lblSpin1) {
                    menuId = INDEX_MENU_HOME_SERVICE;
                }
            } else if (mSelectedMenu == SuggestNameType.CLINIC.getCode()) {
                if (viewId == R.id.lblSpin1) {
                    menuId = INDEX_MENU_CLINIC;
                }
            }
            requestData((TextView) v, menuId);
        }
    };

    private FragmentHome() {
        // mSearchRadioButtons = new RadioButton[4];
        mMainMenu = new ArrayList<ItemRadioSpin>();
    }

    public static FragmentHome newInstance() {
        if (fragmentHome == null)
            fragmentHome = new FragmentHome();
        return fragmentHome;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d("AAAA", "onAttach");
        if (activity instanceof IResult) {
            callIResult = (IResult) activity;
        }
        mMainMenu.clear();
        mMainMenu.add(new ItemRadioSpin(SuggestNameType.DOCTOR.getCode(), getString(R.string.lblTenbacsi)));
        mMainMenu.add(new ItemRadioSpin(SuggestNameType.CLINIC.getCode(), getString(R.string.lblTenphongkham)));
        mMainMenu.add(new ItemRadioSpin(SuggestNameType.HOME_SERVICE.getCode(), getString(R.string.lblDvtainha)));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("AAAA", "onCreateView");
        mView = inflater.inflate(R.layout.fragment_home, null);
        Utils.setOnTouchHideKeyboard(getActivity(), mView);
        mTvSpin1 = (TextView) mView.findViewById(R.id.lblSpin1);
        mTvSpin2 = (TextView) mView.findViewById(R.id.lblSpin2);
        mTvSpin3 = (TextView) mView.findViewById(R.id.lblSpin3);
        mTvSpinMainMenu = (TextView) mView.findViewById(R.id.sp_menu_dichvu);
        mSmessage = (TextView) mView.findViewById(R.id.mSmessage);

        tvCopyRight = (TextView) mView.findViewById(R.id.tvCopyRight);
        tvHotline = (TextView) mView.findViewById(R.id.tvHotline);
        tvEmail = (TextView) mView.findViewById(R.id.tvEmail);

        mLayoutSpin2 = mView.findViewById(R.id.layoutSpin2);
        mTvSpin1.setOnClickListener(mSpinClicked);
        mTvSpin2.setOnClickListener(mSpinClicked);
        mTvSpin3.setOnClickListener(mSpinClicked);
        mTvSpinMainMenu.setOnClickListener(mSpinClicked);
        mSelectedMenu = SuggestNameType.DOCTOR.getCode();
        mSelectedSpin1 = DEFAULT_VALUE;
        mSelectedSpin2 = DEFAULT_VALUE;
        mSelectedSpin3 = DEFAULT_VALUE;
        return mView;
    }

    class DoneOnEditorActionListener implements OnEditorActionListener {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Utils.hideKeyboard(getActivity());
                callIResult.onDisplay(Utils.MAP_ALL_SEARCH_RESULT, "");
                return true;
            }
            return false;
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        callIResult.onDisplay(Utils.TASK_HOME, "");
        Utils.setOnTouchHideKeyboard(getActivity(), mView);

        TextView lblSlogan = (TextView) mView.findViewById(R.id.lblSlogan);
        lblSlogan.setText(Html.fromHtml(getResources().getString(R.string.lblSlogan)));

        adapter = new AutoCompleteAdapter(getActivity(), R.layout.item_autocomplete, new ArrayList<DataItem>());
        mChkSearchByName = (CheckBox) mView.findViewById(R.id.cbSearchbyName);
        mEdkeySearch = (AutoCompleteTextView) mView.findViewById(R.id.edKeySearch);
        mEdkeySearch.setOnEditorActionListener(new DoneOnEditorActionListener());

        mEdkeySearch.setThreshold(1);
        if (isSearchbyName) {
            mEdkeySearch.setVisibility(View.VISIBLE);
            mChkSearchByName.setChecked(true);
        }

        mEdkeySearch.setAdapter(adapter);
        mEdkeySearch.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
                DataItem item = adapter.getItem(pos);
                mEdkeySearch.setText(item.getName());
                Bundle data = new Bundle();
                data.putInt(Utils.KEY_DOCTOR_ID, item.getId());
                data.putInt(Utils.KEY_SERVICE_TYPE, mSelectedMenu);
                Utils.intentToDetailt(getActivity(), Utils.DOCTOR_SERVICE_DETAILT, data);
            }

        });
        mEdkeySearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                if (s.length() < 2) {
                    return;
                }
                ServerController.getInstance(getActivity()).requestGetListSuggestName(new OnRequest<ArrayList<DataItem>>() {

                    @Override
                    public void onSuccess(ArrayList<DataItem> data) {
                        adapter.clear();
                        if (data.isEmpty()) {
                            return;
                        }
                        adapter.addAll(data);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(int errorCode, String message) {
                        // TODO Auto-generated method stub

                    }
                }, s.toString(), mSelectedMenu);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mChkSearchByName.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mChkSearchByName.isChecked()) {
                    mEdkeySearch.setVisibility(View.VISIBLE);
                    isSearchbyName = true;
                } else {
                    mEdkeySearch.setVisibility(View.GONE);
                    isSearchbyName = false;
                }
            }
        });
        // Click search
        Button btnSearch = (Button) mView.findViewById(R.id.btn_search);
        btnSearch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                callIResult.onDisplay(Utils.MAP_ALL_SEARCH_RESULT, "");
            }
        });
        getContactInfo();
        Utils.setOnTouchHideKeyboard(getActivity(), (ViewGroup) mView);

    }

    interface OnRadioCheckedListener {
        public void onChecked(int menu);
    }

    private void requestData(final TextView tvMenu, final int menuId) {
        if (mSelectedSpin1 == DEFAULT_VALUE && mSelectedMenu == SuggestNameType.DOCTOR.getCode()
                && menuId == INDEX_SUB_MENU_SPECIALITY_DETAIL) {
            ArrayList<ItemRadioSpin> items = new ArrayList<ItemRadioSpin>();
            items.add(new ItemRadioSpin(DEFAULT_VALUE, getActivity().getString(R.string.select_khoachitiet)));
            Utils.showDropdow(menuId, getActivity(), items, new IDialogResult() {

                @Override
                public void onResultDropdow(ItemRadioSpin item, int type) {
                    tvMenu.setText(item.getLabel());
                }
            }, null, DEFAULT_VALUE);
            return;
        }
        OnRequest<ArrayList<DataItem>> request = new OnRequest<ArrayList<DataItem>>() {

            @Override
            public void onSuccess(ArrayList<DataItem> data) {
                if (data == null || data.isEmpty()) {
                    Toast.makeText(getActivity(), getActivity().getString(R.string.lbl_khong_co_du_lieu), Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                ArrayList<ItemRadioSpin> items = new ArrayList<ItemRadioSpin>();
                if (menuId == INDEX_MENU_CITY) {
                    items.add(new ItemRadioSpin(0, getActivity().getString(R.string.lbl_tinh_thanh_pho)));
                    items.add(new ItemRadioSpin(-1, getActivity().getString(R.string.lblTimGanban)));
                } else if (menuId == INDEX_MENU_CLINIC) {
                    items.add(new ItemRadioSpin(0, getActivity().getString(R.string.select_loai_phong_kham)));
                } else if (menuId == INDEX_MENU_HOME_SERVICE) {
                    items.add(new ItemRadioSpin(0, getActivity().getString(R.string.select_loai_dich_vu)));
                } else if (menuId == INDEX_SUB_MENU_SPECIALITY_TYPE) {
                    items.add(new ItemRadioSpin(0, getActivity().getString(R.string.select_chuyenkhoa)));
                } else if (menuId == INDEX_SUB_MENU_SPECIALITY_DETAIL) {
                    items.add(new ItemRadioSpin(0, getActivity().getString(R.string.select_khoa)));
                }
                for (DataItem item : data) {
                    items.add(new ItemRadioSpin(item.getId(), item.getName()));
                }
                int selected = 0;
                if (tvMenu.getId() == R.id.lblSpin1) {
                    selected = mSelectedSpin1;
                } else if (tvMenu.getId() == R.id.lblSpin2) {
                    selected = mSelectedSpin2;
                } else if (tvMenu.getId() == R.id.lblSpin3) {
                    selected = mSelectedSpin3;
                }

                Utils.showDropdow(menuId, getActivity(), items, new IDialogResult() {

                    @Override
                    public void onResultDropdow(ItemRadioSpin item, int type) {
                        if (tvMenu.getId() == R.id.lblSpin1) {
                            mSelectedSpin1 = item.getId();
                            resetSpin2();
                        } else if (tvMenu.getId() == R.id.lblSpin2) {
                            mSelectedSpin2 = item.getId();
                        } else if (tvMenu.getId() == R.id.lblSpin3) {
                            mSelectedSpin3 = item.getId();
                            if (mSelectedSpin3 == -1) {
                                // Search nearby
                                LocationServiceManager locationManager = LocationServiceManager.getInstance(getActivity());
                                if (!locationManager.canGetLocation()) {
                                    locationManager.showSettingsAlert();
                                }
                            }
                        }
                        tvMenu.setText(item.getLabel());
                    }
                }, null, selected);
            }

            @Override
            public void onError(int errorCode, String message) {
                String msg = getActivity().getString(R.string.lblErrormessage, errorCode, message);
                if (StatusCode.REQUEST_ERROR == errorCode) {
                    msg = getActivity().getString(R.string.lbl_loi_ket_noi);
                }
                Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
            }
        };

        ServerController controller = ServerController.getInstance(getActivity());

        switch (menuId) {

        case INDEX_SUB_MENU_SPECIALITY_TYPE:
            controller.requestGetSpecialities(request);
            break;
        case INDEX_SUB_MENU_SPECIALITY_DETAIL:
            controller.requestGetSpecialDetail(request, mSelectedSpin1);
            break;
        case INDEX_MENU_CITY:
            controller.requestGetCities(request);
            break;
        case INDEX_MENU_HOME_SERVICE:
            controller.requestGetListHomeServiceType(request);
            break;
        case INDEX_MENU_CLINIC:
            controller.requestGetListClinicType(request);
            break;
        default:
            break;
        }

    }

    public int getSelectedSearchType() {
        return mSelectedMenu;
    }

    public int getSelectedSpin1() {
        return mSelectedSpin1;
    }

    public int getSelectedSpin2() {
        return mSelectedSpin2;
    }

    public int getSelectedSpin3() {
        return mSelectedSpin3;
    }

    public String getSelectedName() {
        if (mChkSearchByName.isChecked()) {
            return mEdkeySearch.getText().toString();
        }
        return "";
    }

    public void getContactInfo() {
        ContactInfoResponse data = Utils.getContactInfo(getActivity());
        if (data == null) {
            requestGetContact(true);
        } else {
            setContactView(data);
        }
       // if(!getActivity().isFinishing())
        //requestGetContact(false);
        
    }

    public void requestGetContact(boolean isLoadding) {
        if (isLoadding)
            MainActivity.mLoadingData.setVisibility(View.VISIBLE);
        ServerController.getInstance(getActivity()).requestGetContact(new OnRequest<ContactInfoResponse>() {

            @Override
            public void onSuccess(ContactInfoResponse data) {
                MainActivity.mLoadingData.setVisibility(View.GONE);

                if (data == null) {
                    return;
                }
                if (data.getCode() == StatusCode.OK&&!getActivity().isFinishing()) {
                    setContactView(data);
                }
                Utils.updateData(getActivity(), Utils.KEY_CONTACT, data);
            }

            @Override
            public void onError(int errorCode, String message) {
                MainActivity.mLoadingData.setVisibility(View.GONE);

            }
        });
    }

    public void setContactView(final ContactInfoResponse data) {
        if (data == null || data.getContactInfo() == null)
            return;
        tvHotline.setText(Html.fromHtml(String.format(getResources().getString(R.string.hot_line), data.getContactInfo()
                .getEasycare_phone())));
        tvEmail.setText(Html.fromHtml(String.format(getResources().getString(R.string.email_support), data.getContactInfo()
                .getEasycare_email())));
        tvCopyRight.setText(Html.fromHtml(data.getContactInfo().getEasycare_copyright()));
        tvHotline.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Utils.callPhone(data.getContactInfo().getEasycare_phone(), getActivity());
            }
        });
    }

}